<template>
    <div class="default-main view-main">
        <div class="view-header">
            <div class="view-title">
                <el-tag type="primary" effect="dark">仪表盘</el-tag>
            </div>
            <div style="flex: 1"></div>
            <div class="view-buttons">
                <el-button type="success" @click="onOpenSystem">平台信息</el-button>
            </div>
        </div>
        <div class="view-body">
            <el-scrollbar>
                <el-row style="margin-top: 10px">
                    <el-col v-for="(item, idx) in state.statistics_list" :key="idx" :span="4">
                        <el-card shadow="hover" style="margin: 5px">
                            <el-statistic v-if="item.enable" :title="item.title" :value="item.num">
                                <template #suffix>/ {{ item.total }}</template>
                            </el-statistic>
                            <el-statistic v-else :title="item.title" :value="item.num"></el-statistic>
                        </el-card>
                    </el-col>
                </el-row>
                <el-row class="dashboard-echarts-container" style="margin-top: 25px">
                    <el-col :span="12">
                        <el-card class="dashboard-echarts">
                            <template #header>
                                <div class="card-header">
                                    <span>CPU</span>
                                    <el-text style="margin-left: 15px" type="primary">进程数 {{ state.cpu.processor_num }}</el-text>
                                </div>
                            </template>
                            <div class="cpu-dashboard-echarts-container">
                                <div id="cpu_echarts" class="cpu-dashboard-echarts"></div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="12">
                        <el-card class="dashboard-echarts">
                            <template #header>
                                <div class="card-header">
                                    <span>内存</span>
                                    <el-text style="margin-left: 15px" type="success">总内存 {{ state.memory.total }}</el-text>
                                    <el-text style="margin-left: 15px" type="warning">已用 {{ state.memory.used }}</el-text>
                                    <el-text style="margin-left: 15px" type="primary">空闲 {{ state.memory.available }}</el-text>
                                </div>
                            </template>
                            <div class="memory-dashboard-echarts-container">
                                <div id="memory_echarts" class="memory-dashboard-echarts"></div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="12">
                        <el-card class="dashboard-echarts">
                            <template #header>
                                <div class="card-header">
                                    <span>网络</span>
                                </div>
                            </template>
                            <div class="network-dashboard-echarts-container">
                                <div id="network_echarts" class="network-dashboard-echarts"></div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="12">
                        <el-card class="dashboard-echarts">
                            <template #header>
                                <div class="card-header">
                                    <span>硬盘</span>
                                </div>
                            </template>
                            <div class="disk-dashboard-echarts-container">
                                <div id="disk_echarts" class="disk-dashboard-echarts"></div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </el-scrollbar>
        </div>
        <SipDialog></SipDialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive, provide } from 'vue';
import api from '@/api';
import { DashboardState } from '@/views/admin/dashboard/interface';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import SipDialog from '@/views/admin/dashboard/SipDialog.vue';

defineOptions({
    name: 'AdminDashboard',
});

const state = reactive<DashboardState>(new DashboardState());

const onLoadDashboardStatistics = () => {
    api.post('/api/web/dashboard/statistics', {})
        .then((res) => {
            if (res && res.data) {
                state.statistics_list = res.data.statistics_list;
            }
        })
        .catch((error) => {
            console.error(error);
            ElMessage.error(`code: ${error.code} msg: ${error.msg}`);
        });
};

const num = 30;
const onLoadDashboardInfo = () => {
    api.post('/api/web/dashboard/info', {})
        .then((res) => {
            if (res && res.data) {
                state.cpu = res.data.cpu;
                state.memory = res.data.memory;
                state.disk = res.data.disk;
                if (res.data.network) {
                    if (state.network.xAxis.data.length >= num) {
                        state.network.xAxis.data.shift();
                        state.network.series[0].data.shift();
                        state.network.series[1].data.shift();
                    }
                    // @ts-ignore
                    state.network.xAxis.data.push(res.data.network.time);
                    // @ts-ignore
                    state.network.series[0].data.push(res.data.network.send);
                    // @ts-ignore
                    state.network.series[1].data.push(res.data.network.accept);
                }
                initCPU();
                initMemory();
                initNetwork();
                initDisk();
            }
        })
        .catch((error) => {
            console.error(error);
        });
};

const onLoadDashboardSIP = () => {
    api.post('/api/web/dashboard/sip', {})
        .then((res) => {
            if (res && res.data) {
                state.dialog.sip.id = res.data.ip;
                state.dialog.sip.domain = res.data.domain;
                state.dialog.sip.ip = res.data.ip;
                state.dialog.sip.port = res.data.port;
                state.dialog.sip.password = res.data.password;
            }
        })
        .catch((error) => {
            console.error(error);
        });
};

const initCPU = () => {
    if (state.echarts.cpu === undefined) {
        let dom = document.getElementById('cpu_echarts');
        state.echarts.cpu = echarts.init(dom);
    }
    let xData: Array<string> = [];
    let yData: Array<number> = [];
    for (let i = 0; i < state.cpu.rate_list.length; i++) {
        let item = state.cpu.rate_list[i];
        xData.push(item.time);
        yData.push(item.rate);
    }
    state.echarts.cpu &&
        state.echarts.cpu.setOption({
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: xData,
                axisLabel: {
                    rotate: 45,
                },
            },
            yAxis: {
                type: 'value',
                min: 0,
                max: 100,
            },
            series: [
                {
                    data: yData,
                    type: 'line',
                    areaStyle: {},
                },
            ],
        });
};

const initMemory = () => {
    if (state.echarts.memory === undefined) {
        let dom = document.getElementById('memory_echarts');
        state.echarts.memory = echarts.init(dom);
    }
    let xData: Array<string> = [];
    let yData: Array<number> = [];
    for (let i = 0; i < state.memory.rate_list.length; i++) {
        let item = state.memory.rate_list[i];
        xData.push(item.time);
        yData.push(item.rate);
    }
    state.echarts.memory &&
        state.echarts.memory.setOption({
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: xData,
                axisLabel: {
                    rotate: 45,
                },
            },
            yAxis: {
                type: 'value',
                min: 0,
                max: 100,
            },
            series: [
                {
                    data: yData,
                    type: 'line',
                    areaStyle: {},
                },
            ],
        });
};

const initNetwork = () => {
    if (state.echarts.network === undefined) {
        let dom = document.getElementById('network_echarts');
        state.echarts.network = echarts.init(dom);
    }
    state.echarts.network && state.echarts.network.setOption(state.network);
};

const initDisk = () => {
    if (state.echarts.disk === undefined) {
        let dom = document.getElementById('disk_echarts');
        state.echarts.disk = echarts.init(dom);
    }
    let yData: Array<string> = [];
    let usedData: Array<string> = [];
    let freeData: Array<string> = [];
    let len = state.disk.list.length;
    for (let i = len - 1; i >= 0; i--) {
        let item = state.disk.list[i];
        yData.push(item.path);
        usedData.push(item.used);
        freeData.push(item.free);
    }
    state.echarts.disk &&
        state.echarts.disk.setOption({
            xAxis: {
                type: 'value',
            },
            yAxis: {
                type: 'category',
                data: yData,
            },
            series: [
                {
                    name: '已用',
                    type: 'bar',
                    stack: 'total',
                    label: {
                        show: true,
                    },
                    emphasis: {
                        focus: 'series',
                    },
                    data: usedData,
                },
                {
                    name: '空闲',
                    type: 'bar',
                    stack: 'total',
                    label: {
                        show: true,
                    },
                    emphasis: {
                        focus: 'series',
                    },
                    data: freeData,
                },
            ],
        });
};

const onOpenSystem = () => {
    state.dialog.sip.show = true;
};

onMounted(() => {
    onLoadDashboardStatistics();
    state.statistics_timer = window.setInterval(
        () => {
            onLoadDashboardStatistics();
        },
        1000 * 60 * 5
    );
    onLoadDashboardInfo();
    state.info_timer = window.setInterval(() => {
        onLoadDashboardInfo();
    }, 1000);
    onLoadDashboardSIP();
});
onUnmounted(() => {
    window.clearInterval(state.statistics_timer);
    window.clearInterval(state.info_timer);
});

// 绑定属性
provide('state', state);
</script>
